<?php
// Communication between the server and the extension
// Request 1: Check if user in into the link and send back the available message (check the type of page)
// Request 2: Insert the user and the link into database
// Request 3: Delete the link from user


// DATABASE
define ("EXIST", "1");
define ("NOT_EXIST", "2");
define ("OK", "3");

// ERRORS
define ("DB_ERR", "-1");
define ("REQ_ERR", "-2");
define ("URL_ERR", "-3");
define ("FB_ERR", "-4");

function error($errno) {
	$response="ERROR $errno";
	$UserName="null";
	echo $_GET["jsoncallback"] . "({\"UserName\":\"". $UserName . "\", \"response\":\" " . $response . "\"})";
	die();
}

function check_database($user, $link) {
	$con = mysql_connect ("localhost:3306", "root", "fli2411");
        if (!$con) {
		error(DB_ERR);
        }
        mysql_select_db("brain_browser", $con);
	$res = mysql_query ("SELECT * FROM user_link WHERE user='$user' AND link='$link'", $con);
	$num_rows = mysql_num_rows($res);
	mysql_close($con);

	if ($num_rows==0)	return NOT_EXIST;
	else	return EXIST;
	
}

function InsertToDatabase($user, $link) {
	$con = mysql_connect ("localhost:3306", "root", "fli2411");
        if (!$con) {
		error(DB_ERR);
        }
	mysql_select_db("brain_browser", $con);
	mysql_query("INSERT INTO user_link (user, link) VALUES ('$user', '$link')", $con);
	mysql_close($con);
	return OK;
}

function DeleteFromDatabase($user, $link) {
	$con = mysql_connect ("localhost:3306", "root", "fli2411");
        if (!$con) {
		error(DB_ERR);
        }
	mysql_select_db("brain_browser", $con);
	mysql_query("DELETE FROM user_link WHERE user = '$user' AND  link = '$link'", $con);
	mysql_close($con);
	return OK;
}

require '../php-sdk/src/facebook.php';

$response="Unknown Error!";

//READ req
if (!isset($_GET["req"]))	error(REQ_ERR);
else if ($_GET["req"]=="1")	$req="1";
else if ($_GET["req"]=="2")	$req="2";
else	error(REQ_ERR);

// READ URL
if (!isset($_GET["Link"]))	error(URL_ERR);
else $link = $_GET["Link"];

// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
	'appId'  => '176213615761250',
	'secret' => '375110a154f2a4f5b2f6e4f8f093f7be',
	'cookie' => true,
));




// Get User ID
$user = $facebook->getUser();

	

	$user_check = "";
if ($user) {
	try {
	// Proceed knowing you have a logged in user who's authenticated.
		$user_profile = $facebook->api('/me');
		$check_res = check_database($user, $link);
		$UserName_arr = explode(" ", $user_profile['name']);
		$UserName = $UserName_arr[0];
		
		if ($check_res == NOT_EXIST) {
			if ($req=="1"){
				$response= "not_exist";
			}
			else if ($req=="2") {
				
				InsertToDatabase($user, $link);
				$response = "inserted";
			}
		}
		else if ($check_res == EXIST) {
			if ($req=="1"){
				$response = "exist";
			}
			else if ($req=="2") {
				DeleteFromDatabase($user, $link);
				$response = "deleted";
			}
		}
		
		$user_check = "$user_profile[name]";
	} catch (FacebookApiException $e) {
		error(FB_ERR);
	}
}
else {

// 		$params = array(
// 			'scope' => 'offline_access',
// 			'redirect_uri' => 'http://cyberang3l.ath.cx:33335/',
// 		);

	$loginUrl = $facebook->getLoginUrl(array(
		'canvas' => 1,
		'fbconnect' => 0,
		'scope' => 'offline_access'
	));
	//$args['redirect_uri'] = "http://cyberang3l.ath.cx:33335/index.php";
	//$loginUrl = $facebook->getLoginUrl($args);
	$response = "not_logged_in";
	$UserName=$loginUrl;
}

//echo $_GET["jsoncallback"] . "({\"Message\":\"" . $Message . "\"})";
echo $_GET["jsoncallback"] . "({\"UserName\":\"". $UserName . "\", \"response\":\"" . $response . "\", \"user_check\":\"" . $user_check . "\"})";
?>

